﻿package  {
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextFormat;
	
	
	public class Main extends MovieClip {
		var conn:IMConnection;
		
		public function Main() {
			
			
			// constructor code
			conn=new IMConnection("xen.xugp.com",5000);
			//conn=new IMConnection("192.168.2.103",5000);
			//conn=new IMConnection("192.168.2.103",5000);
			conn.addEventListener(Event.CONNECT,onConnConnect);
			conn.addEventListener(IMEvent.LOGINOK,onLoginOK);
			conn.addEventListener(IMEvent.RECVMSG,onRecvMsg);
			conn.addEventListener(IMEvent.RECVSYSMSG,onRecvSysMsg);
			conn.addEventListener(IMEvent.SENDMSGOK,onSendMsgOK);
			conn.addEventListener(IMEvent.SENDMSGERROR,onSendMsgError);
			conn.addEventListener(IMEvent.CMDERROR,onCmdError);
			
			btnLogin.addEventListener(MouseEvent.CLICK,onBtnLoginClick);
			btnSendMsg.addEventListener(MouseEvent.CLICK,onBtnSendMsgClick);
		}
		
		public function addmsg(msg:String):void{
			txtMsgs.appendText(msg + "\n");
			
			txtMsgs.verticalScrollPosition=txtMsgs.maxVerticalScrollPosition;
		}
		
		public function onConnConnect(evt:Event){
			addmsg("连接成功");
		}
		
		public function onBtnSendMsgClick(evt:MouseEvent){
			conn.SendMsg(edPeerUserID.text,edMsgContent.text);
		}
		
		public function onBtnLoginClick(evt:MouseEvent):void{
			conn.Login(edUserID.text);
		}
		
		public function onCmdError(evt:IMEvent):void{
			addmsg(evt.content);
		}
		
		public function onLoginOK(evt:IMEvent):void{
			addmsg("登录成功");
		}
		
		public function onSendMsgOK(evt:IMEvent):void{
			//addmsg("SendMsg OK");
			edMsgContent.text="";
		}
		
		public function onSendMsgError(evt:IMEvent):void{
			addmsg("SendMsg Error," + evt.content);
		}
		
		
		public function onRecvMsg(evt:IMEvent):void{
			var fromuserid:String=evt.fromuserid;
			var touserid:String=evt.touserid;
			if(fromuserid==conn.myuserid){
				fromuserid="我";
			}
			
			if(touserid==conn.myuserid){
				touserid="我";
			}else if(touserid=="*"){
				touserid="大家";
			}
			
			addmsg(fromuserid + " 对 " + touserid + "说：" + evt.msgconetnt);
		}
		
		public function onRecvSysMsg(evt:IMEvent):void{
			addmsg("系统消息：" + evt.content);
		}
	}
	
}
